package com.fqgj.sentry.biz.mc;


import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.fqgj.sentry.biz.mc.domain.AddUserInfo;
import com.fqgj.sentry.biz.mc.domain.RedisOperate;
import com.fqgj.sentry.biz.mc.vo.user.GroupManagerVo;
import com.fqgj.sentry.biz.mc.vo.user.UserVo;
import com.fqgj.sentry.common.exception.BizException;
import com.fqgj.sentry.common.exception.enums.ErrorCodeEnums;
import com.fqgj.sentry.common.utils.ApiPage;
import com.fqgj.sentry.common.utils.EmailUtils;
import com.fqgj.sentry.common.utils.HashUtils;
import com.fqgj.sentry.common.utils.RandomStringUtils;
import com.fqgj.sentry.manage.entity.McGroupManagerEntity;
import com.fqgj.sentry.manage.entity.McUserEntity;
import com.fqgj.sentry.manage.enums.UserLevelEnums;
import com.fqgj.sentry.manage.service.BaseInfoService;
import com.fqgj.sentry.manage.service.GroupManagerService;
import com.fqgj.sentry.manage.service.UserService;
import com.github.pagehelper.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


/**
 * Created by ykpbean kangping.ying@yuntu-inc.com
 *
 * @description
 * @create 2017-07-12 下午12:57
 */

@Component
public class UserBusiness {
    private static Log logger = LogFactory.getLog(UserBusiness.class);

    @Autowired
    private UserService userService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private GroupManagerService groupManagerService;
    @Autowired
    private BaseInfoService baseInfoService;


    public Long addUser(AddUserInfo addUserInfo) {
        //生成对应的密码并发送给对应邮箱 邮箱需要在插入完成后进行发送
        String password = RandomStringUtils.getPasswordComplex(8);
//        String password ="123456";
        McUserEntity mcUserEntity = new McUserEntity()
                .setPassword(HashUtils.md5(password))
                .setAccount(addUserInfo.getAccount())
                .setMerchantId(addUserInfo.getMerchantId())
                .setLevel(addUserInfo.getLevel())
                .setMobile(addUserInfo.getMobile())
                .setName(addUserInfo.getName());
        McUserEntity userEntity = userService.insertUser(mcUserEntity);
        try {
            EmailUtils.sendSimpleMail(addUserInfo.getAccount(), "Password mail", "Your initial password in sentry-admin is: " + password + "，Please modify it in time。");
        } catch (Exception e) {
            logger.error("sendSimpleMail error", e);
            throw new BizException(ErrorCodeEnums.email_send_error);
        }
        return userEntity.getId();
    }

    public Boolean addGroupManager(Long merchantId, Long userId, List<String> rolesIdCode, String appIdCode) {

        List<Long> rolesId = new ArrayList<>();
        for (String roleIdCode : rolesIdCode) {
//            rolesId.add(Long.valueOf(AESUtils.decrypt(roleIdCode)));
            rolesId.add(Long.valueOf(roleIdCode));
        }
        Long appId = Long.valueOf(appIdCode);
        return groupManagerService.addGroupManager(merchantId, userId, rolesId, appId);
    }

    public Boolean delUser(Long userId, Long merchantId) {
//        Long userId = Long.valueOf(AESUtils.decrypt(userIdCode));
        userService.deleteUser(userId, merchantId);
        RedisOperate.delRedisUserCache(redisClient, userId);
        return true;
    }

    public Boolean delGroupManager(Long groupManagerId) {
//        Long userId = Long.valueOf(AESUtils.decrypt(userIdCode));
//        Long appId = Long.valueOf(AESUtils.decrypt(appIdCode));
        return groupManagerService.deleteGroupManager(groupManagerId);
    }

    public Boolean modifyGroupManger(Long groupManagerId, List<Long> rolesId) {
        return groupManagerService.updateGroupManager(groupManagerId, rolesId);
    }

    public Boolean resetPassword(Long userId, Long merchantId) {
        //重置密码需要重新生成 新密码并发送至对方邮箱
//        String password = RandomStringUtils.getPasswordComplex(8);
        String password = "123456";
        McUserEntity userEntity = baseInfoService.selectBaseInfo(userId);
        if (!merchantId.equals(userEntity.getMerchantId())) {
            throw new BizException(ErrorCodeEnums.merchant_user_error, "您要重置密码的用户不在当前商户下");
        }
        if (userEntity.getLevel().equals(UserLevelEnums.merchant_admin)) {
            throw new BizException(ErrorCodeEnums.merchant_level_error, "该用户是商户系统管理员，你无法重置密码");
        }
        userEntity.setPassword(HashUtils.md5(password))
                .setGmtModified(new Date());
        baseInfoService.updateBaseInfo(userEntity);
        String email = userEntity.getAccount();
        try {
            EmailUtils.sendSimpleMail(email, "Password mail", "Your initial password in sentry-admin is ：" + password + "，Please modify it in time。");
        } catch (Exception e) {
            logger.error("sendSimpleMail error", e);
            throw new BizException(ErrorCodeEnums.email_send_error);
        }
        return true;
    }

    public ApiPage queryUserListForPage(String account, Long merchantId, Integer pageNum, Integer pageSize) {
        Page<McUserEntity> page = userService.selectUserListForPage(account, merchantId, pageNum, pageSize);
        List<UserVo> userVoList = new ArrayList<>();
        for (McUserEntity mcuserentity : page.getResult()) {
            UserVo userVo = new UserVo();
            String userIdCode = String.valueOf(mcuserentity.getId());
            userVo.setUserId(userIdCode).setName(mcuserentity.getName())
                    .setAccount(mcuserentity.getAccount()).setLevel(mcuserentity.getLevel())
                    .setMobile(mcuserentity.getMobile())
                    .setGmtModified(mcuserentity.getGmtModified());
            userVoList.add(userVo);
        }
        ApiPage apiPage = new ApiPage()
                .setPageNum(pageNum)
                .setPageSize(pageSize)
                .setTotal(page.getTotal())
                .setData(userVoList);

        return apiPage;
    }

    public List<GroupManagerVo> queryGroupManagerByUserId(Long userId) {
        List<McGroupManagerEntity> groupManagerEntityList = groupManagerService.selectListByUserId(userId);

        List<GroupManagerVo> groupManagerVoList = new LinkedList<>();

        for (McGroupManagerEntity groupManagerEntity : groupManagerEntityList) {
            GroupManagerVo groupManagerVo = new GroupManagerVo();
            BeanUtils.copyProperties(groupManagerEntity, groupManagerVo);
            groupManagerVoList.add(groupManagerVo);
        }
        return groupManagerVoList;
    }


}
